﻿using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using CRM.Extensions;
using System.Threading.Tasks;
using CRM.Models;
using CRM.Services;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Authorization;

namespace CRM.Controllers.Email
{
    [Route("api/[controller]")]
    [ApiController]
    public class EmailVerifyController : BaseController
    {
        private readonly MyDbContext _dbContext;
        private readonly UserManager<User> _userManager;

        private readonly AnyleadsService _anyleadsService;
        // private readonly ILogger<EmailConfigController> _logger;

        public EmailVerifyController(MyDbContext dbContext, UserManager<User> userManager, AnyleadsService anyleadsService)
        {
            _dbContext = dbContext;
            _userManager = userManager;
            _anyleadsService = anyleadsService;
        }

        [HttpGet(nameof(Index))]
        public async Task<ResultStruct> Index()
        {
            var user = await _userManager.GetUserAsync(User);
            var result = await _dbContext.EmailVerifyLogs
                .Where(m => m.OemId == user.OemId && m.CompanyId == user.CompanyId && m.GroupId == user.GroupId && m.UserId == user.Id)
                .ToPaginateAsync(Request);
            return Success(result);
        }

        public record VerifyVm(string Email = "");
        public record BatchVerifyVm(List<string> Email);

        // [HttpPost("[action]")]
        // public async Task<ResultStruct> Verify(VerifyVm vm)
        // {
        //     var result = await _anyleadsService.ValidateEmail(vm.Email);
        //     return Success(new {State = result});
        // }

        [HttpPost("[action]")]
        public async Task<ResultStruct> Verify(BatchVerifyVm vm)
        {
            var result = await _anyleadsService.ValidateEmail(vm.Email);
            return Success(result);
        }

        [HttpPost("cverify")]
        [AllowAnonymous]
        public async Task<ResultStruct> ClientVerify(BatchVerifyVm vm)
        {
            if (!Request.Query.TryGetValue("key", out var value) || value != "test-crm")
            {
                return Error("未授权");
            }

            _anyleadsService.CurrentUser = new Models.User()
            {
                Id = 1,
                OemId = 1,
                GroupId = 1,
                CompanyId = 1,
            };

            var result = await _anyleadsService.ValidateEmail(vm.Email);
            return Success(result);
        }

    }
}